package gov.kqqzyyy.monkey.tjpd.ui;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.view.KeyEvent;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SynthesizerListener;
import com.socks.library.KLog;

import java.lang.ref.WeakReference;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import gov.kqqzyyy.monkey.tjpd.R;
import gov.kqqzyyy.monkey.tjpd.adapter.PatientAdapter;
import gov.kqqzyyy.monkey.tjpd.broadcast.UpdateReceiver;
import gov.kqqzyyy.monkey.tjpd.mytools.CurrentVersion;
import gov.kqqzyyy.monkey.tjpd.mytools.DateUtil;
import gov.kqqzyyy.monkey.tjpd.mytools.MyBaseActivity;
import gov.kqqzyyy.monkey.tjpd.mytools.MyServiceUtil;
import gov.kqqzyyy.monkey.tjpd.mytools.MyStringUtil;
import gov.kqqzyyy.monkey.tjpd.mytools.SpeakTool;
import gov.kqqzyyy.monkey.tjpd.objects.TJ_DDDL;
import gov.kqqzyyy.monkey.tjpd.objects.TJ_ZSXX;
import gov.kqqzyyy.monkey.tjpd.service.UpdateService;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class MainActivity extends MyBaseActivity {

    @BindView(R.id.home_main)
    RelativeLayout relativeLayout;
    @BindView(R.id.title_text)
    TextView titleText;
    @BindView(R.id.num_text_1)
    TextView currentNum;
    @BindView(R.id.num_text_2)
    TextView patientNum;
    @BindView(R.id.patient_name)
    TextView patientName;
    @BindView(R.id.patient_wait_listview)
    ListView patientListView;
    @BindView(R.id.warn_text)
    TextView warnText;
    @BindView(R.id.qr_code_img)
    SimpleDraweeView qrCodeImg;
    @BindView(R.id.datetime_text)
    TextView dateTimeText;
    @BindView(R.id.warn_num_text)
    TextView warnNumText;
    @BindView(R.id.version_text)
    TextView versionText;

    private Intent serviceIntent;

    private UpdateReceiver updateReceiver;

    private boolean isStoped = false;

    private Bitmap bgbmp;

    private int zsid;

    private Call<String> dddlCall;
    private Call<String> updateCall;

    private List<TJ_DDDL> dddlList;

    private PatientAdapter adapter;

    private Timer scrollTimer;
    private Timer clockTimer;
    private boolean moveToBottom = true;
    private boolean loadQRCode;

    private MyHandler handler;
//    private CallThered callThered;

    private TJ_ZSXX tj_zsxx;
    private SpeakTool speakTool;

//    private boolean isGettingInfo = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        ButterKnife.bind(this);

        serviceIntent = new Intent(getApplicationContext(), UpdateService.class);
        updateReceiver = new UpdateReceiver(this);
        IntentFilter updateFilter = new IntentFilter("updatebroadcast");
        registerReceiver(updateReceiver, updateFilter);

        bgbmp = readBitMap(R.drawable.main_bg);
        relativeLayout.setBackground(new BitmapDrawable(getResources(), bgbmp));

        adapter = new PatientAdapter(this);
        patientListView.setAdapter(adapter);

        handler = new MyHandler(this);

        speakTool = new SpeakTool(this);

        doSetTime();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setVersionText();

        loadQRCode = true;
        zsid = Integer.valueOf(getMySharedPreferences().getString("clinic_preference", "-1"));
        if (zsid == -1) {
            Toast.makeText(getApplicationContext(), "请先设置诊室！", Toast.LENGTH_SHORT).show();
        } else {
            String clinicName = getMySharedPreferences().getString("clinicarea_name", "");
            String infoText = clinicName + "排队信息";
            titleText.setText(infoText);

            String temp = getResources().getString(R.string.warn_text);
            String textTemp = String.format(temp, clinicName);
            warnText.setText(textTemp);

            doStartService();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        isStoped = true;
        if (dddlCall != null && dddlCall.isExecuted()) {
            dddlCall.cancel();
        }
        if (updateCall != null && updateCall.isExecuted()) {
            updateCall.cancel();
        }
        if (clockTimer != null) {
            clockTimer.cancel();
        }

        doStopScroll();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        unregisterReceiver(updateReceiver);

        if (!bgbmp.isRecycled()) {
            bgbmp.recycle();
            bgbmp = null;
            relativeLayout.setBackground(null);
        }
        if (speakTool != null) {
            speakTool.destory();
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch (keyCode) {
            case KeyEvent.KEYCODE_MENU:
                Intent intent = new Intent(getApplicationContext(), FragmentPreferences.class);
                startActivity(intent);
                finish();
                return true;
            case KeyEvent.KEYCODE_BACK:
                finish();
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    // 更新提示对话框
    public void showUpdateDialog(int newVerCode, String newVerName) {
        cancelProgressDialog();
        String message = "";
        final Intent intent = new Intent("toUpdateService");
        message += "当前版本：" + CurrentVersion.getVerName(this) + "\n";
        message += "版本号：" + CurrentVersion.getVerCode(this) + "\n";
        message += "发现新版本：" + newVerName + "\n";
        message += "版本号：" + newVerCode + "\n";
        message += "是否更新？";
        Dialog dialog = new AlertDialog.Builder(this)
                .setTitle("软件更新")
                .setMessage(message)
                .setCancelable(false)
                .setPositiveButton("确定", (dialogInterface, i) -> {
                    intent.putExtra("toservice", 0x11);
                    sendBroadcast(intent);
                    dialogInterface.dismiss();
                    showProgressDialog("下载中");
                })
                .setNegativeButton("取消", (dialogInterface, i) -> dialogInterface.dismiss())
                .create();
        dialog.show();
    }

    public void doFlushData(int which) {
        if (!isStoped) {
            switch (which) {
                case 1:
                    doGetZsxx(zsid);
                    break;
                case 2:
                    doGetdddl();
                    break;
            }
        }
    }

    public void doStartService() {
        startService(serviceIntent);
    }

    @Override
    protected void doSetZsxx(TJ_ZSXX tjZsxx) {
        super.doSetZsxx(tjZsxx);
        if (tjZsxx == null) {
            timeToGetInfo(1);
        } else {
            if (!tjZsxx.equals(tj_zsxx) || tjZsxx.getHj() == 0) {
                tj_zsxx = tjZsxx;
                if (tj_zsxx.getSfqy() == 0) {
                    warnNumText.setText(R.string.warn_num_text_2);
                    warnText.setText(R.string.warn_text_2);
                    qrCodeImg.setImageURI("");//清除图片，加载默认占位符图片
                    loadQRCode = true;//下次重新加载二维码
                    timeToGetInfo(1);
                } else {
                    warnNumText.setText(R.string.warn_num_text);
                    String temp = getResources().getString(R.string.warn_text);
                    String textTemp = String.format(temp, tj_zsxx.getZsmc());
                    warnText.setText(textTemp);

                    if (loadQRCode) {
                        loadQRCode = false;
                        Uri uri = Uri.parse(tj_zsxx.getImgurl());
                        qrCodeImg.setImageURI(uri);
                    }
                    if (tj_zsxx.getDqh() == 0) {
                        timeToGetInfo(1);
                    } else {
                        String dqhText = tj_zsxx.getDqh() + "";
                        currentNum.setText(dqhText);
                        patientNum.setText(tj_zsxx.getDqbh());
                        patientName.setText(MyStringUtil.doHideName(tj_zsxx.getDqry()));
                        if (tj_zsxx.getHj() == 0) {
                            doCallPatient();
                        } else {
                            timeToGetInfo(1);
                        }
                    }
                }

            } else {
                timeToGetInfo(1);
            }

        }
    }

    private void doCallPatient() {
        new CallThered(tj_zsxx).start();
    }

    private void timeToGetInfo(int which) {
        CountDownTimer timer = new CountDownTimer(10000, 5000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                if (which == 1) {
                    doGetZsxx(zsid);
                } else {
                    doGetdddl();
                }
            }
        };
        timer.start();
    }

    //获取等待队列
    private void doGetdddl() {
        dddlCall = MyServiceUtil.getDddlCall(zsid);
        Callback<String> callback = new Callback<String>() {
            @Override
            public void onResponse(@NonNull Call<String> call, Response<String> response) {
                Gson gson = new Gson();
                String result = response.body();
                if (result != null) {
                    dddlList = gson.fromJson(result, new TypeToken<List<TJ_DDDL>>() {
                    }.getType());
                    if (dddlList != null && dddlList.size() > 0) {
                        adapter.setList(dddlList);
                        patientListView.smoothScrollToPosition(0);
                        doStartScroll();
                    } else {
                        timeToGetInfo(2);
                    }
                } else {
                    timeToGetInfo(2);
                }

            }

            @Override
            public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {
                timeToGetInfo(2);
            }
        };
        dddlCall.enqueue(callback);

    }

    private void doRollingListView() {
        if (dddlList != null && dddlList.size() > 0) {
            int lastPos = patientListView.getLastVisiblePosition();
            if (lastPos < dddlList.size() - 1) {
                if (moveToBottom) {
                    moveToBottom = false;
                    patientListView.smoothScrollToPosition(lastPos);
                } else {
                    moveToBottom = true;
                    patientListView.smoothScrollToPosition(lastPos + 1);
                }
            } else {
                if (moveToBottom) {
                    patientListView.smoothScrollToPosition(dddlList.size() - 1);
                } else {
                    doStopScroll();
                    doFlushData(2);
//                    timeToGetInfo(2);
                }
                moveToBottom = !moveToBottom;
            }
        }
    }

    private void doStopScroll() {
        if (scrollTimer != null) {
            scrollTimer.cancel();
            scrollTimer = null;
        }
    }

    private void doStartScroll() {
        doStopScroll();
        scrollTimer = new Timer();
        scrollTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                doRollingListView();
            }
        }, 5000, 5000);
    }

    private void doSetTime() {
        clockTimer = new Timer();
        clockTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                Message message = new Message();
                message.what = 0x11;
                handler.sendMessage(message);
            }
        }, 1000, 1000);

    }

    private void setClock() {
        Date localDate = new Date(System.currentTimeMillis());
        String showDate = DateUtil.getWeekFormatDate(localDate);
        dateTimeText.setText(showDate);
    }

    private static class MyHandler extends Handler {
        WeakReference<MainActivity> mActivity;

        MyHandler(MainActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MainActivity activity = mActivity.get();
            switch (msg.what) {
                case 0x11:
                    activity.setClock();
                    break;
                case 0x29:
                    activity.tj_zsxx.setHj(1);
                    activity.doGetZsxx(activity.zsid);
                    break;
            }
        }
    }

    private class CallThered extends Thread {

        TJ_ZSXX tjZsxx;

        CallThered(TJ_ZSXX tj_zsxx) {
            this.tjZsxx = tj_zsxx;
        }

        @Override
        public void run() {
            super.run();
            String speakMessage = "请 " + tjZsxx.getDqh() + "号 " + tjZsxx.getDqry() + " 到 " + tjZsxx.getZsmc() + " 检查";
            speakMessage += " " + speakMessage;
            int result = speakTool.speak(speakMessage, listener);
            KLog.d("APE", result);
            if (result == 0) { //语音成功
                doUpdateHJ(tjZsxx.getId());
            } else {
                doGetZsxx(zsid);
            }
        }

        //语音状态监听
        private SynthesizerListener listener = new SynthesizerListener() {
            @Override
            public void onSpeakBegin() {
                KLog.d("APE", "speak begin");
            }

            @Override
            public void onBufferProgress(int percent, int beginPos, int endPos, String info) {

            }

            @Override
            public void onSpeakPaused() {

            }

            @Override
            public void onSpeakResumed() {

            }

            @Override
            public void onSpeakProgress(int percent, int beginPos, int endPos) {

            }

            @Override
            public void onCompleted(SpeechError speechError) {
                KLog.d("APE", "speak complete");
                Message message1 = new Message();
                message1.what = 0x29;
                handler.sendMessage(message1);
            }

            @Override
            public void onEvent(int i, int i1, int i2, Bundle bundle) {
            }
        };

    }

    private void doUpdateHJ(int id) {
        updateCall = MyServiceUtil.updateHJ(id);
        Callback<String> callback = new Callback<String>() {
            @Override
            public void onResponse(@NonNull Call<String> call, Response<String> response) {
                String result = response.body();
                if (result != null) {
                    KLog.d("APE", result);
                }
            }

            @Override
            public void onFailure(@NonNull Call<String> call, @NonNull Throwable t) {

            }
        };
        updateCall.enqueue(callback);
    }

    public void setVersionText() {
        if (versionText != null) {
            String text = "版本号：" + CurrentVersion.getVerName(this);
            versionText.setText(text);
        }
    }

}
